package com.example.sunmiv1.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.ReportLossListAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.base.bean;
import com.example.sunmiv1.entity.LossGoodsInfo;
import com.example.sunmiv1.entity.ReportLossGoodBean;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewReportLossActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.reportLoss_chooseFood_btn)
    LinearLayout reportLossChooseFoodBtn;
    @BindView(R.id.reportLossSearch_edit)
    EditText reportLossSearchEdit;
    @BindView(R.id.reportLossSearch_code_new)
    ImageView reportLossSearchCodeNew;
    @BindView(R.id.reportLossSearch_search_new)
    ImageView reportLossSearchSearchNew;
    @BindView(R.id.view_top)
    LinearLayout viewTop;
    @BindView(R.id.reportLoss_new_listView)
    ListView reportLossNewListView;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;
    @BindView(R.id.reportLoss_new_checkAll)
    TextView reportLossNewCheckAll;
    @BindView(R.id.reportLoss_new_submit)
    TextView reportLossNewSubmit;
    @BindView(R.id.ll_save_and_submit)
    LinearLayout llSaveAndSubmit;
    @BindView(R.id.reportLoss_new_complete)
    TextView reportLossNewComplete;
    @BindView(R.id.reportLoss_new_delete)
    TextView reportLossNewDelete;
    @BindView(R.id.reportLoss_new_operation)
    LinearLayout reportLossNewOperation;
    @BindView(R.id.view_footer)
    LinearLayout viewFooter;
    @BindView(R.id.reportLoss_remark)
    EditText reportLossRemark;
    @BindView(R.id.reportLoss_remarkLin)
    LinearLayout reportLossRemarkLin;
    @BindView(R.id.reportLoss_scanFood_btn)
    LinearLayout reportLossScanFoodBtn;

    private ArrayList<String> notInIdArr;// 已在此頁的貨物id  添加和選擇2個頁面都要維護這個列表
    private List<LossGoodsInfo.DataBean> choiceList;
    public static boolean opera = false;
    private ReportLossListAdapter adapter;
    private LoadingDialog loadingDialog;
    private ACache aCache;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_new_report_loss);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.newReportLossTitle);
        loadingDialog = new LoadingDialog(this);
        aCache = ACache.get(this);
    }

    @Override
    protected void initData() {
        notInIdArr = new ArrayList<>();
        choiceList = new ArrayList<>();
    }

    @Override
    protected void initListener() {

    }

    @OnClick({R.id.title_back, R.id.reportLoss_chooseFood_btn, R.id.reportLossSearch_code_new, R.id.reportLossSearch_search_new,
            R.id.btn_to_top, R.id.reportLoss_new_checkAll, R.id.reportLoss_new_submit, R.id.reportLoss_new_complete,
            R.id.reportLoss_new_delete, R.id.reportLoss_new_operation, R.id.reportLoss_scanFood_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.reportLoss_scanFood_btn:
                scanGood(1, choiceList);
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.reportLoss_chooseFood_btn:
                Intent intent = new Intent(this, ReportLossSearchActivity.class);
                intent.putStringArrayListExtra("not_in_ids", notInIdArr);
                startActivityForResult(intent, 100);
                break;
            case R.id.reportLossSearch_code_new://掃碼
                startQrCode();
                break;
            case R.id.reportLossSearch_search_new:
                if (TextUtils.isEmpty(reportLossSearchEdit.getText().toString().trim())) {
                    Toast.makeText(this, "請輸入貨號/條碼/名稱", Toast.LENGTH_SHORT).show();
                    return;
                }
                boolean flag = false;
                String info = reportLossSearchEdit.getText().toString().trim();
                for (int i = 0; i < choiceList.size(); i++) {
                    if (info.equals(choiceList.get(i).getGoods_code())) {
                        flag = true;
                        reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        reportLossNewListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                reportLossNewListView.setSelection(finalI);
                            }
                        }, 800);
                        adapter.setSelect(i);
                        break;
                    }
                    if (info.equals(choiceList.get(i).getSku_code())) {
                        flag = true;
                        reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        reportLossNewListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                reportLossNewListView.setSelection(finalI);
                            }
                        }, 800);
                        adapter.setSelect(i);
                        break;
                    }
                    if (info.equals(choiceList.get(i).getGoods_number())) {
                        flag = true;
                        reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        reportLossNewListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                reportLossNewListView.setSelection(finalI);
                            }
                        }, 800);
                        adapter.setSelect(i);
                        break;
                    }
                    if (info.equals(choiceList.get(i).getSku_goods_number())) {
                        flag = true;
                        reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        reportLossNewListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                reportLossNewListView.setSelection(finalI);
                            }
                        }, 800);
                        adapter.setSelect(i);
                        break;
                    }
                    if (info.equals(choiceList.get(i).getGoods_name())) {
                        flag = true;
                        reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        reportLossNewListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                reportLossNewListView.setSelection(finalI);
                            }
                        }, 800);
                        adapter.setSelect(i);
                        break;
                    }
                }
                if (!flag) {
                    Toast.makeText(this, "已選列表中暫無該商品", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_to_top:
                reportLossNewListView.setSelection(0);
                break;
            case R.id.reportLoss_new_checkAll:
                opera = true;
                if (llSaveAndSubmit.getVisibility() == View.GONE) {
                    if ("全選".equals(reportLossNewCheckAll.getText().toString().trim())) {
                        for (LossGoodsInfo.DataBean dataBean : choiceList) {
                            dataBean.setChecked(true);
                        }
                        setAdapter();
                        reportLossNewCheckAll.setText(R.string.purRefundAdding_Choose_Item_Check_None);
                    } else {
                        for (LossGoodsInfo.DataBean dataBean : choiceList) {
                            dataBean.setChecked(false);
                        }
                        setAdapter();
                        reportLossNewCheckAll.setText(R.string.purRefundAdding_check_all);
                    }
                } else {
                    llSaveAndSubmit.setVisibility(View.GONE);
                    reportLossNewOperation.setVisibility(View.VISIBLE);
                    reportLossNewCheckAll.setText(R.string.purRefundAdding_check_all);
                }
                setAdapter();
                break;
            case R.id.reportLoss_new_submit:
                if (choiceList.size() == 0) {
                    Toast.makeText(this, "請先選擇商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < choiceList.size(); i++) {
                    if (TextUtils.isEmpty(choiceList.get(i).getLoss_num())) {
                        Toast.makeText(this, "請先輸入" + choiceList.get(i).getGoods_name() + "的報損數量", Toast.LENGTH_SHORT).show();
                        reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        reportLossNewListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                reportLossNewListView.setSelection(finalI);
                            }
                        }, 800);
                        adapter.setSelect(i);
                        return;
                    }
                    if (Double.parseDouble(choiceList.get(i).getLoss_num()) > choiceList.get(i).getGoods_num()) {
                        Toast.makeText(this, "報損數量不能超過系統庫存", Toast.LENGTH_SHORT).show();
                        reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        reportLossNewListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                reportLossNewListView.setSelection(finalI);
                            }
                        }, 800);
                        adapter.setSelect(i);
                        return;
                    }
                }
                new AlertDialog.Builder(this).setTitle("提示")//設置對話框標題
                        .setMessage("確定要提交報損？")//設置顯示的內容
                        .setPositiveButton("確定", (dialog, which) -> {//確定按鈕的響應事件
                            submitInventory();
                        }).setNegativeButton("取消", (dialog, which) -> {//取消按鈕的響應事件
                }).show();//顯示此對話框
                break;
            case R.id.reportLoss_new_complete:
                opera = false;
                llSaveAndSubmit.setVisibility(View.VISIBLE);
                reportLossNewOperation.setVisibility(View.GONE);
                reportLossNewCheckAll.setText(R.string.operation);
                setAdapter();
                break;
            case R.id.reportLoss_new_delete:
                for (int i = choiceList.size() - 1; i >= 0; i--) {
                    if (choiceList.get(i).isChecked()) {
                        notInIdArr.remove(choiceList.get(i).getId());
                        choiceList.remove(i);
                    }
                }
                setAdapter();
                break;
            case R.id.reportLoss_new_operation:

                break;
        }
    }

    private void setAdapter() {
        if (adapter == null) {
            adapter = new ReportLossListAdapter(NewReportLossActivity.this, choiceList);
            reportLossNewListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        if (choiceList.size() == 0) {
            reportLossRemark.setText("");
            reportLossRemarkLin.setVisibility(View.GONE);
        } else {
            reportLossRemarkLin.setVisibility(View.VISIBLE);
        }
        adapter.setChoose(index -> {
            Intent intent = new Intent(context, StringCodeOperationActivity.class);
            intent.putExtra("operation", 5);
            intent.putExtra("good", choiceList.get(index));
            startActivityForResult(intent, 200);
        });
    }

    /*提交盤點*/
    private void submitInventory() {
        reportLossNewSubmit.setEnabled(false);
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        String url = "";
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            if ("2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
                url = Common.STORE_LOSS_OPERATION;
                jsonObject.put("storeid", aCache.getAsString("storeid"));
            } else if ("1".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
                url = Common.LOSS_OPERATION;
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
                url = Common.STORE_LOSS_OPERATION;
                jsonObject.put("storeid", aCache.getAsString("storeid"));
            }
            for (int i = 0; i < choiceList.size(); i++) {
                JSONObject json = new JSONObject();
                json.put("id", choiceList.get(i).getId());
                json.put("warehouse_id", choiceList.get(i).getWarehouse_id());
                json.put("goods_id", choiceList.get(i).getGoods_id());
                json.put("goods_name", choiceList.get(i).getGoods_name());
                json.put("goods_number", choiceList.get(i).getGoods_number());
                json.put("goods_code", choiceList.get(i).getGoods_code());
                json.put("attribute_state", choiceList.get(i).getAttribute_state());
                json.put("sku_id", choiceList.get(i).getSku_id());
                json.put("sku_code", choiceList.get(i).getSku_code());
                json.put("sku_name", choiceList.get(i).getSku_name());
                json.put("sku_num", choiceList.get(i).getSku_num());
                json.put("sku_goods_number", choiceList.get(i).getSku_goods_number());
                json.put("goods_num", choiceList.get(i).getGoods_num());
                json.put("more_num", choiceList.get(i).getMore_num());
                json.put("less_num", choiceList.get(i).getLess_num());
                json.put("loss_num", choiceList.get(i).getLoss_num());
                json.put("cost_price", choiceList.get(i).getCost_price());
                json.put("remarks", choiceList.get(i).getRemark());
                jsonArray.put(json);
            }
            jsonObject.put("goodsList", jsonArray);
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("remarks", reportLossRemark.getText().toString().trim());
            Log.d("傳參",jsonObject.toString());
            HttpUtils.post(this, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    reportLossNewSubmit.setEnabled(true);
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            finish();
//                            choiceList.clear();
//                            setAdapter();
                        }
                        Toast.makeText(NewReportLossActivity.this, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    reportLossNewSubmit.setEnabled(true);
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.REQ_QR_CODE:
                    Bundle bundle = data.getExtras();
                    reportLossSearchEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    String info = reportLossSearchEdit.getText().toString().trim();
                    boolean flag = false;
                    for (int i = 0; i < choiceList.size(); i++) {
                        if (info.equals(choiceList.get(i).getGoods_code())) {
                            flag = true;
                            reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            reportLossNewListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    reportLossNewListView.setSelection(finalI);
                                }
                            }, 800);
                            adapter.setSelect(i);
                            break;
                        }
                        if (info.equals(choiceList.get(i).getSku_code())) {
                            flag = true;
                            reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            reportLossNewListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    reportLossNewListView.setSelection(finalI);
                                }
                            }, 800);
                            adapter.setSelect(i);
                            break;
                        }
                        if (info.equals(choiceList.get(i).getGoods_number())) {
                            flag = true;
                            reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            reportLossNewListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    reportLossNewListView.setSelection(finalI);
                                }
                            }, 800);
                            adapter.setSelect(i);
                            break;
                        }
                        if (info.equals(choiceList.get(i).getSku_goods_number())) {
                            flag = true;
                            reportLossNewListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            reportLossNewListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    reportLossNewListView.setSelection(finalI);
                                }
                            }, 800);
                            adapter.setSelect(i);
                            break;
                        }
                    }
                    if (!flag) {
                        Toast.makeText(this, "已選列表中暫無該商品", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 100://選擇商品返回的數據
                    List<LossGoodsInfo.DataBean> backList = (List<LossGoodsInfo.DataBean>) data.getSerializableExtra("choice_list");
                    for (LossGoodsInfo.DataBean dataBean : backList) {
                        dataBean.setChecked(false);
                        notInIdArr.add(dataBean.getId());
                    }
                    choiceList.addAll(backList);
                    setAdapter();
                    break;
                case 110:
                    List<LossGoodsInfo.DataBean> s = (List<LossGoodsInfo.DataBean>) data.getSerializableExtra("list");
                    for (LossGoodsInfo.DataBean dataBean : s) {
                        dataBean.setChecked(false);
                        notInIdArr.add(dataBean.getId());
                    }
                    choiceList.clear();
                    choiceList.addAll(s);
                    setAdapter();
                    break;
                case 200:
                    LossGoodsInfo.DataBean bean = (LossGoodsInfo.DataBean) data.getSerializableExtra("bean");
                    int index = 0;
                    for (int t = 0; t < choiceList.size(); t++) {
                        if (bean.getGoods_id().equals(choiceList.get(t).getGoods_id())) {
                            if ("2".equals(bean.getAttribute_state())) {
                                if (bean.getSku_id().equals(choiceList.get(t).getSku_id())) {
                                    index = t;
                                    break;
                                }
                            } else {
                                index = t;
                                break;
                            }
                        }
                    }
                    choiceList.set(index, bean);
                    setAdapter();
                    break;
            }
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
